<?php
/**
 * CreateTime: 2022/6/28 10:44
 */

namespace App\Tools\File;

use App\Consts\ResponseConsts\ResponseStatusConsts;
use App\Exports\Export;
use App\Exports\AllExport;
use App\Func\ResponseFunc;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;

class ExcelFile
{

    public function fileExport($head,$data,$excelName = ""){
        // 设置最大导出时间
        ini_set('max_execution_time', 60000);
        ini_set('memory_limit', '256M');
        $fmtHead = [];
        foreach($head as $key => $value){
            $fmtHead[$value] = $value;
        }
        $fileName = "excel".DIRECTORY_SEPARATOR.$excelName.time().random_int(0,99999).".xlsx";
        $fileInfo =  Excel::store(new Export([$fmtHead],$data),$fileName);
//        $fileInfo =  Excel::store(new AllExport(),$fileName);
        if($fileInfo){
             return response()->
             download(Storage::disk('local')->path($fileName))
                 ->deleteFileAfterSend();
        }else{
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                null,
                '导出失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            ));
        }

    }

    public function fileAllExport($head,$data,$table,$excelName = ""){
        // 设置最大导出时间
        ini_set('max_execution_time', 0);
        ini_set('memory_limit', '256M');
        $fmtHead = [];
        foreach($head as $key => $value){
            $fmtHead[$value] = $value;
        }
        if(!is_dir(storage_path().DIRECTORY_SEPARATOR."app".DIRECTORY_SEPARATOR."excel")){
            mkdir(storage_path().DIRECTORY_SEPARATOR."app".DIRECTORY_SEPARATOR."excel");
        }
        $fileName = "excel".DIRECTORY_SEPARATOR.$excelName.time().random_int(0,99999).".xlsx";
        $exportStatus = new AllExport($data,$table,$head);

        $fileInfo =  Excel::store($exportStatus,$fileName);

        if($fileInfo){
            return $fileName;
        }else{
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                null,
                '导出失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            ));
        }

    }
}